package cn.com.twoke.get_xml_data.ui.impl;

import cn.com.twoke.get_xml_data.config.ThreadPoolConfiguration;
import cn.com.twoke.get_xml_data.service.GetXmlDataHandler;
import cn.com.twoke.get_xml_data.service.GetXmlDataType;
import cn.com.twoke.get_xml_data.ui.GetXmlDataInfoFrame;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class GetXmlDataInfoFrameImpl extends JFrame implements GetXmlDataInfoFrame {
    private final JFileChooser fileChooser;
    private File[] selectedFiles;
    private Boolean selectedFileFlag = Boolean.FALSE;

    public GetXmlDataInfoFrameImpl() {
        setTitle("Get XML Data Info");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(false);
        setLayout(null);
        setIconImage(new ImageIcon("resources/image/icon.png").getImage());
        setBounds(100, 100, 450, 300);
        this.fileChooser = new JFileChooser(System.getProperty("user.dir"));
        this.fileChooser.setFileFilter(new XmlDataFileFilter());
        this.fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        this.fileChooser.setMultiSelectionEnabled(true);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                System.exit(0);
            }
        });

        JLabel showSelectedFileLabel = new JLabel("未选中XML日志文件");
        showSelectedFileLabel.setBounds(210,5,235, 28);
        add(showSelectedFileLabel);

        JButton selectXMlDataFile = createSelectXmlDataFileButton(showSelectedFileLabel);
        add(selectXMlDataFile);


        GetXmlDataType[] values = GetXmlDataType.values();          //定义字符串
        JComboBox<GetXmlDataType> comboBox = new JComboBox<GetXmlDataType>(values);
        comboBox.setBounds(315, 38, 100, 28);
        add(comboBox);

        JProgressBar progressBar = new JProgressBar();
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        progressBar.setBounds(5, 71 , 425, 10);
        add(progressBar);

        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(); // 创建滚动条面板
        scrollPane.setBounds(5, 86, 425, 170); // 设置滚动条面板位置和大小
        scrollPane.setViewportView(textArea);
        add(scrollPane);

        JButton startGetData = createStartGetXmlDataButton(progressBar, textArea, comboBox);
        add(startGetData);

        JButton cleanLogInfo = new JButton("清除日志");
        cleanLogInfo.setBounds(210, 38, 100, 28);
        cleanLogInfo.addActionListener(e -> {
            synchronized (textArea) {
                textArea.setText("");
            }
        });
        add(cleanLogInfo);




    }

    private final static String OUTPUT_DIR = System.getProperty("user.dir") + File.separator + "result";

    private JButton createStartGetXmlDataButton(JProgressBar progressBar,JTextArea textArea,
                                                JComboBox<GetXmlDataType> comboBox) {
        JButton startGetData = new JButton("开始截取数据");
        startGetData.setBounds(5,38,200, 28);
        startGetData.addActionListener(e -> {
            synchronized (progressBar) {
                progressBar.setValue(0);
            }
            GetXmlDataHandler xmlDataHandler = ((GetXmlDataType) Objects.requireNonNull(comboBox.getSelectedItem())).
                    get(textArea, OUTPUT_DIR);
            if (!this.selectedFileFlag) {
                JOptionPane.showMessageDialog(this, "请先选择XML日志文件", "提示",JOptionPane.WARNING_MESSAGE);
                return;
            }
            ThreadPoolConfiguration.EXECUTOR_SERVICE.execute(() -> {
                int fileIndex = 0;
                AtomicInteger count = new AtomicInteger(0);
                for (File selectedFile : this.selectedFiles) {
                    String fileNo = String.format("%8s", fileIndex).replace(" ", "0");
                    ThreadPoolConfiguration.EXECUTOR_SERVICE.execute(() -> {
                        try {
                            xmlDataHandler.handle(fileNo, selectedFile);
                            synchronized (progressBar) {
                                double doubleValue =  count.incrementAndGet();
                                int value = (int) (doubleValue / selectedFiles.length * 100.00);
                                progressBar.setValue(value);
                            }
                            synchronized (textArea) {
                                textArea.append("完成数据截取：(" + fileNo + ")" + selectedFile.getAbsolutePath() + "\n");
                            }
                        } catch (Exception ex) {
                            synchronized (textArea) {
                                textArea.append("数据截取失败：(" + fileNo + ")" + selectedFile.getAbsolutePath() + " 错误信息：" + ex.getMessage() + "\n");
                            }
                        }
                    });
                    fileIndex++;
                }
            });
        });
        return startGetData;
    }

    private JButton createSelectXmlDataFileButton(JLabel showSelectedFileLabel) {
        JButton selectXMlDataFile = new JButton("选择XML日志文件");
        selectXMlDataFile.setBounds(5,5, 200, 28);
        selectXMlDataFile.addActionListener(e -> {
            int i = this.fileChooser.showOpenDialog(this);
            if (i == JFileChooser.APPROVE_OPTION) {
                this.selectedFiles = this.fileChooser.getSelectedFiles();
                showSelectedFileLabel.setText("选中XML日志文件个数：" + this.selectedFiles.length);
                this.selectedFileFlag = Boolean.TRUE;
            } else {
                showSelectedFileLabel.setText("未选中XML日志文件");
                this.selectedFileFlag = Boolean.FALSE;
            }
        });
        return selectXMlDataFile;
    }


    public void open() {
        setVisible(true);
    }

    public void close() {
        setVisible(false);
    }


    private static class XmlDataFileFilter extends FileFilter {

        @Override
        public boolean accept(File f) {
            if (f.isDirectory())return true;
            return f.getName().endsWith(".xml");
        }

        @Override
        public String getDescription() {
            return "XML文件(*.xml)";
        }
    }
}
